// mall.js
Page({
  data: {
    categories: [],
    products: [],
    allProducts: [], // 存储所有产品数据
    currentCategory: 0,
    hasMore: true,
    page: 1,
    pageSize: 10,
    loading: false,
    // 搜索相关
    searchKeyword: '',
    searchFocus: false,
    isSearching: false,
    searchHistory: [], // 搜索记录
    showSearchHistory: false, // 是否显示搜索记录
    // 推荐产品
    recommendedProducts: [], // 推荐产品列表
    showRecommendations: true, // 是否显示推荐产品
    // AI对话
    aiMessages: [], // AI对话消息列表
    aiInputText: '', // AI输入框文本
    aiLoading: false, // AI是否正在处理
    scrollToView: '', // 滚动到指定消息
    showAiChatDialog: false // 控制AI对话弹窗显示隐藏
  },

  onLoad() {
    this.loadProducts()
    this.loadSearchHistory()
    this.loadRecommendations()
  },

  // 添加欢迎消息
  addWelcomeMessage() {
    const now = new Date()
    const time = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`
    
    const welcomeMessage = {
      type: 'ai',
      content: '您好！我是AI智能助手，请告诉我您的需求，我会为您推荐合适的产品。\n\n例如：\n• 我需要一个颈椎按摩器\n• 最近肩膀疼，有什么推荐\n• 想买一些养生用品',
      time: time,
      products: null
    }
    
    this.setData({
      aiMessages: [welcomeMessage]
    })
  },

  // 加载商品数据
  loadProducts() {
    if (this.data.loading) return
    
    this.setData({ loading: true })
    
    wx.request({
      url: 'http://localhost:8081/product/productAll',
      method: 'GET',
      success: (res) => {
        console.log('商品数据API响应:', res.data)
        
        if (res.statusCode === 200 && res.data) {
          const products = Array.isArray(res.data) ? res.data : []
          
          // 处理产品数据
          const processedProducts = products.map(product => ({
            id: product.id,
            name: product.name,
            cover: product.cover || 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=300&h=300&fit=crop&crop=center',
            price: product.price || 0,
            originalPrice: product.originalPrice || 0,
            sales: product.sales || 0,
            stock: product.stock || 0,
            categoryId: product.categoryId,
            category: product.category,
            intro: product.intro || '',
            detail: product.detail || '',
            status: product.status || 1
          }))
          
          // 提取分类信息
          const categoryMap = new Map()
          categoryMap.set(0, { id: 0, name: '全部' })
          
          processedProducts.forEach(product => {
            if (product.category && !categoryMap.has(product.categoryId)) {
              categoryMap.set(product.categoryId, {
                id: product.categoryId,
                name: product.category.name,
                icon: product.category.icon
              })
            }
          })
          
          const categories = Array.from(categoryMap.values())
          
          this.setData({
            allProducts: processedProducts,
            products: processedProducts,
            categories: categories,
            hasMore: false,
            loading: false
          })
          
          console.log('商品数据加载完成:', {
            totalProducts: processedProducts.length,
            categories: categories.length
          })
        } else {
          console.error('商品数据API返回错误:', res)
          this.setData({ loading: false })
          wx.showToast({
            title: '加载商品失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('获取商品数据失败:', err)
        this.setData({ loading: false })
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      }
    })
  },

  // 分类点击事件
  onCategoryTap(e) {
    const categoryId = parseInt(e.currentTarget.dataset.id)
    console.log('选择分类:', categoryId)
    
    this.setData({ 
      currentCategory: categoryId
    })
    
    this.filterProductsByCategory(categoryId)
  },

  // 根据分类筛选商品
  filterProductsByCategory(categoryId) {
    let filteredProducts = this.data.allProducts
    
    if (categoryId !== 0) {
      filteredProducts = this.data.allProducts.filter(product => 
        product.categoryId === categoryId
      )
    }
    
    // 如果正在搜索，需要同时应用搜索筛选
    if (this.data.isSearching && this.data.searchKeyword) {
      filteredProducts = this.filterProductsByKeyword(filteredProducts, this.data.searchKeyword)
    }
    
    this.setData({
      products: filteredProducts
    })
    
    console.log('筛选结果:', {
      categoryId: categoryId,
      totalProducts: this.data.allProducts.length,
      filteredProducts: filteredProducts.length,
      isSearching: this.data.isSearching
    })
  },

  // 搜索输入事件
  onSearchInput(e) {
    const keyword = e.detail.value
    this.setData({
      searchKeyword: keyword,
      showSearchHistory: keyword === '' // 输入为空时显示搜索记录
    })
    
    // 实时搜索（防抖处理）
    clearTimeout(this.searchTimer)
    this.searchTimer = setTimeout(() => {
      if (keyword.trim()) {
        this.performSearch(keyword.trim())
      } else {
        this.clearSearch()
      }
    }, 300)
  },

  // 搜索框获得焦点
  onSearchFocus() {
    this.setData({
      searchFocus: true,
      showSearchHistory: this.data.searchKeyword === ''
    })
  },

  // 搜索框失去焦点
  onSearchBlur() {
    this.setData({
      searchFocus: false,
      showSearchHistory: false
    })
  },

  // 搜索确认事件
  onSearchConfirm() {
    const keyword = this.data.searchKeyword.trim()
    if (keyword) {
      this.performSearch(keyword)
    } else {
      this.clearSearch()
    }
  },

  // 执行搜索
  performSearch(keyword) {
    console.log('执行搜索:', keyword)
    
    this.setData({
      isSearching: true,
      searchFocus: false,
      showSearchHistory: false
    })
    
    // 保存搜索记录
    this.saveSearchHistory(keyword)
    
    // 搜索所有产品
    const searchResults = this.filterProductsByKeyword(this.data.allProducts, keyword)
    
    this.setData({
      products: searchResults,
      currentCategory: 0 // 搜索时重置分类
    })
    
    console.log('搜索结果:', {
      keyword: keyword,
      totalProducts: this.data.allProducts.length,
      searchResults: searchResults.length
    })
    
    // 显示搜索结果提示
    if (searchResults.length === 0) {
      wx.showToast({
        title: '未找到相关商品',
        icon: 'none'
      })
    } else {
      wx.showToast({
        title: `找到${searchResults.length}个商品`,
        icon: 'none'
      })
    }
  },

  // 根据关键词筛选商品
  filterProductsByKeyword(products, keyword) {
    if (!keyword) return products
    
    const lowerKeyword = keyword.toLowerCase()
    
    return products.filter(product => {
      // 搜索商品名称
      if (product.name && product.name.toLowerCase().includes(lowerKeyword)) {
        return true
      }
      
      // 搜索商品介绍
      if (product.intro && product.intro.toLowerCase().includes(lowerKeyword)) {
        return true
      }
      
      // 搜索商品详情
      if (product.detail && product.detail.toLowerCase().includes(lowerKeyword)) {
        return true
      }
      
      // 搜索分类名称
      if (product.category && product.category.name && 
          product.category.name.toLowerCase().includes(lowerKeyword)) {
        return true
      }
      
      return false
    })
  },

  // 清除搜索
  onClearSearch() {
    this.clearSearch()
  },

  // 清除搜索状态
  clearSearch() {
    console.log('清除搜索')
    
    this.setData({
      searchKeyword: '',
      isSearching: false,
      searchFocus: false,
      showSearchHistory: false
    })
    
    // 恢复原始筛选
    this.filterProductsByCategory(this.data.currentCategory)
  },

  // 加载搜索记录
  loadSearchHistory() {
    try {
      const history = wx.getStorageSync('mall_search_history') || []
      this.setData({
        searchHistory: history
      })
    } catch (error) {
      console.error('加载搜索记录失败:', error)
    }
  },

  // 保存搜索记录
  saveSearchHistory(keyword) {
    if (!keyword || keyword.trim() === '') return
    
    try {
      let history = wx.getStorageSync('mall_search_history') || []
      
      // 移除重复项
      history = history.filter(item => item !== keyword)
      
      // 添加到开头
      history.unshift(keyword)
      
      // 限制最多保存10条记录
      if (history.length > 10) {
        history = history.slice(0, 10)
      }
      
      // 保存到本地存储
      wx.setStorageSync('mall_search_history', history)
      
      // 更新页面数据
      this.setData({
        searchHistory: history
      })
    } catch (error) {
      console.error('保存搜索记录失败:', error)
    }
  },

  // 点击搜索记录
  onHistoryItemTap(e) {
    const keyword = e.currentTarget.dataset.keyword
    this.setData({
      searchKeyword: keyword,
      showSearchHistory: false
    })
    this.performSearch(keyword)
  },

  // 删除搜索记录
  onDeleteHistory(e) {
    const keyword = e.currentTarget.dataset.keyword
    e.stopPropagation() // 阻止事件冒泡
    
    try {
      let history = wx.getStorageSync('mall_search_history') || []
      history = history.filter(item => item !== keyword)
      
      wx.setStorageSync('mall_search_history', history)
      
      this.setData({
        searchHistory: history
      })
      
      wx.showToast({
        title: '已删除',
        icon: 'success'
      })
    } catch (error) {
      console.error('删除搜索记录失败:', error)
    }
  },

  // 清空搜索记录
  onClearHistory() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空所有搜索记录吗？',
      success: (res) => {
        if (res.confirm) {
          try {
            wx.removeStorageSync('mall_search_history')
            this.setData({
              searchHistory: []
            })
            wx.showToast({
              title: '已清空',
              icon: 'success'
            })
          } catch (error) {
            console.error('清空搜索记录失败:', error)
          }
        }
      }
    })
  },

  // 商品点击事件
  onProductTap(e) {
    const productId = e.currentTarget.dataset.id
    console.log('点击商品:', productId)
    
    wx.navigateTo({
      url: `/pages/product-detail/product-detail?id=${productId}`,
      success: () => {
        console.log('跳转到商品详情页成功')
      },
      fail: (err) => {
        console.error('跳转失败:', err)
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        })
      }
    })
  },

  // 加载推荐产品
  loadRecommendations() {
    const app = getApp()
    const userInfo = app.getUserInfo()
    
    if (!userInfo || !userInfo.isLogin) {
      console.log('用户未登录，不加载推荐产品')
      return
    }
    
    const userId = userInfo.userId || userInfo.id
    if (!userId) {
      console.log('用户ID不存在，不加载推荐产品')
      return
    }
    
    console.log('开始加载推荐产品，用户ID:', userId)
    
    wx.request({
      url: `http://localhost:8081/product/getRecommendations?userId=${userId}&limit=6`,
      method: 'GET',
      success: (res) => {
        console.log('推荐产品API响应:', res.data)
        
        if (res.statusCode === 200 && Array.isArray(res.data)) {
          const recommendedProducts = res.data.map(product => ({
            id: product.id,
            name: product.name,
            cover: product.cover || 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=300&h=300&fit=crop&crop=center',
            price: product.price || 0,
            originalPrice: product.originalPrice || 0,
            sales: product.sales || 0,
            stock: product.stock || 0,
            categoryId: product.categoryId,
            category: product.category,
            intro: product.intro || '',
            detail: product.detail || '',
            status: product.status || 1
          }))
          
          this.setData({
            recommendedProducts: recommendedProducts
          })
          
          console.log('推荐产品加载完成:', recommendedProducts.length)
        } else {
          console.error('推荐产品API返回错误:', res)
        }
      },
      fail: (err) => {
        console.error('获取推荐产品失败:', err)
      }
    })
  },

  // 推荐产品点击事件
  onRecommendationTap(e) {
    const productId = e.currentTarget.dataset.id
    console.log('点击推荐产品:', productId)
    
    wx.navigateTo({
      url: `/pages/product-detail/product-detail?id=${productId}`,
      success: () => {
        console.log('跳转到推荐产品详情页成功')
      },
      fail: (err) => {
        console.error('跳转失败:', err)
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        })
      }
    })
  },

  // 隐藏推荐产品
  onHideRecommendations() {
    this.setData({
      showRecommendations: false
    })
  },

  // 显示推荐产品
  onShowRecommendations() {
    this.setData({
      showRecommendations: true
    })
  },

  // AI输入变化
  onAiInputChange(e) {
    const value = e.detail.value
    console.log('AI输入变化:', value, '长度:', value ? value.length : 0)
    
    this.setData({
      aiInputText: value
    })
  },

  // 发送AI消息
  onAiSendMessage() {
    const message = this.data.aiInputText
    if (!message || message.length === 0 || this.data.aiLoading) {
      console.log('发送条件不满足:', {
        message: message,
        messageLength: message ? message.length : 0,
        aiLoading: this.data.aiLoading
      })
      return
    }

    // 去除首尾空格
    const trimmedMessage = message.trim()
    if (trimmedMessage.length === 0) {
      console.log('消息为空，无法发送')
      return
    }

    console.log('发送AI消息:', trimmedMessage)

    // 添加用户消息
    this.addMessage('user', trimmedMessage)
    
    // 清空输入框
    this.setData({
      aiInputText: '',
      aiLoading: true
    })

    // 调用AI推荐API
    this.callAiRecommendApi(trimmedMessage)
  },

  // 调用AI推荐API
  callAiRecommendApi(query) {
    const app = getApp()
    const userInfo = app.getUserInfo()
    const userId = userInfo && userInfo.isLogin ? (userInfo.userId || userInfo.id) : null

    wx.request({
      url: `http://localhost:8081/product/aiRecommend?query=${encodeURIComponent(query)}${userId ? '&userId=' + userId : ''}`,
      method: 'GET',
      success: (res) => {
        console.log('AI推荐API响应:', res.data)
        
        this.setData({
          aiLoading: false
        })

        if (res.data && res.data.code === 200) {
          // 添加AI回复消息
          this.addMessage('ai', res.data.aiResponse, res.data.products)
        } else {
          // 添加错误消息
          this.addMessage('ai', res.data?.message || '抱歉，我暂时无法为您推荐产品，请稍后再试。')
        }
      },
      fail: (err) => {
        console.error('AI推荐API调用失败:', err)
        
        this.setData({
          aiLoading: false
        })
        
        // 添加错误消息
        this.addMessage('ai', '网络错误，请检查网络连接后重试。')
      }
    })
  },

  // 添加消息到对话列表
  addMessage(type, content, products = null) {
    const messages = this.data.aiMessages
    const now = new Date()
    const time = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`
    
    const newMessage = {
      type: type,
      content: content,
      time: time,
      products: products
    }
    
    messages.push(newMessage)
    
    this.setData({
      aiMessages: messages,
      scrollToView: `message-${messages.length - 1}`
    })

    // 延迟滚动到底部
    setTimeout(() => {
      this.setData({
        scrollToView: `message-${messages.length - 1}`
      })
    }, 100)
  },

  // AI推荐产品点击事件
  onAiProductTap(e) {
    const productId = e.currentTarget.dataset.id
    console.log('点击AI推荐产品:', productId)
    
    wx.navigateTo({
      url: `/pages/product-detail/product-detail?id=${productId}`,
      success: () => {
        console.log('跳转到AI推荐产品详情页成功')
      },
      fail: (err) => {
        console.error('跳转失败:', err)
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        })
      }
    })
  },

  // 切换AI对话弹窗显示状态
  onToggleAiChatDialog() {
    console.log('切换AI对话弹窗，当前状态:', this.data.showAiChatDialog)
    
    this.setData({
      showAiChatDialog: !this.data.showAiChatDialog
    })
    
    // 如果显示弹窗且没有消息，添加欢迎消息
    if (this.data.showAiChatDialog && this.data.aiMessages.length === 0) {
      this.addWelcomeMessage()
    }
    
    // 调试信息
    if (this.data.showAiChatDialog) {
      console.log('AI弹窗已显示，应该居中显示在屏幕中间')
    }
  },

  // 关闭AI对话弹窗
  onCloseAiChatDialog() {
    this.setData({
      showAiChatDialog: false
    })
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 空函数，用于阻止事件冒泡
  },

  // 清空AI对话
  onClearAiChat() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空AI对话记录吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            aiMessages: []
          })
          wx.showToast({
            title: '对话已清空',
            icon: 'success'
          })
        }
      }
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadProducts()
    this.loadRecommendations()
    wx.stopPullDownRefresh()
  }
})
